package com.lhy.admin.mp.web;

import com.lhy.admin.common.mvcplus.entity.RespResult;
import com.lhy.admin.common.secure.authentication.Anon;
import com.lhy.admin.mp.propoties.WechatMpProperties;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("wechat")
@Slf4j
public class WxIndexController {

    @Autowired
    WxMpService wxMpService;

    @Autowired
    WechatMpProperties wechatMpProperties;

    /**
     * IndexController
     * <p/>
     * 主页，可以直接配置在微信菜单里
     *
     * @author hyluan
     * @date 2018/8/3 17:59
     * Copyright (c) 2018 wisedu
     */
    @RequestMapping(value = "/index")
    @SneakyThrows
    @Anon
    public String index(String code, String state, HttpSession session) {
        log.info("访问主页：code：{}，state:{}", code, state);
        //未授权 通过微信oauth授权 跳转
        if (!StringUtils.hasText(code)) {
            String url = wechatMpProperties.getIndex();
            String redirectUrl = wxMpService.getOAuth2Service().buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_BASE, state);
            log.info("跳转地址：{}", redirectUrl);
            return "redirect:" + redirectUrl;
        } else {
            if ("debug".equals(code)) {
                log.info("设置 debug session openId:{}", wechatMpProperties.getTestOpenId());
                session.setAttribute("openId", wechatMpProperties.getTestOpenId());
                return redirectPage(state);
            }
            //已通过微信oauth授权，跳转主页
            WxOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.getOAuth2Service().getAccessToken(code);
            log.info("accessToken:{}", wxMpOAuth2AccessToken.getAccessToken());
            log.info("设置session openId:{}", wxMpOAuth2AccessToken.getOpenId());
            session.setAttribute("openId", wxMpOAuth2AccessToken.getOpenId());
            return redirectPage(state);
        }
    }

    private String redirectPage(String state) {
        if (!StringUtils.hasText(state)) {
            return "redirect:/app.html";
        }
        return "redirect:/app.html#/" + state;
    }

    @GetMapping(value = "config")
    @ResponseBody
    public RespResult config() {
        return RespResult.ok().setData(wechatMpProperties);
    }
}
